﻿using System.Diagnostics;
using System.Security.Claims;
using JetBrains.Annotations;
using Volo.Abp;

namespace Ly.EBussiness.EntityFrameworkCore.Auth.User;

public static class ClaimsIdentityExtensions
{
    public static string? FindUserId([NotNull] this ClaimsPrincipal principal)
    {
        Check.NotNull(principal, nameof(principal));
        var userIdOrNull = principal.Claims?.FirstOrDefault(c =>
            c.Type is CustomClaimTypes.UserId or ClaimTypes.NameIdentifier);
        if (userIdOrNull == null || userIdOrNull.Value.IsNullOrWhiteSpace())
        {
            return null;
        }
        return userIdOrNull.Value;
    }
}

public static class CurrentUserExtensions
{
    public static string? FindClaimValue(this ICurrentUser currentUser, string claimType)
    {
        return currentUser.FindClaim(claimType)?.Value;
    }

    public static T FindClaimValue<T>(this ICurrentUser currentUser, string claimType)
        where T : struct
    {
        var value = currentUser.FindClaimValue(claimType);
        if (value == null)
        {
            return default;
        }

        return value.To<T>();
    }

    public static string? GetId(this ICurrentUser currentUser)
    {
        Debug.Assert(currentUser.Id != null, "currentUser.Id != null");

        return currentUser.Id;
    }
}